import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {SiteInfo, Good} from 'src/utils/server.interface'
import Skeleton from 'taro-skeleton';
import {View, Image, Text, Block} from '@tarojs/components'
import {AtIcon, AtRate} from 'taro-ui'
import {http} from '../../utils/http'
import {RESOURCE_URL, STORE_INFO, STORE_PAGE, TARO_ENV} from '../../constants/api'
import {GetRequest, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../utils/lx.h5.service";
import GoodsBox from '../../pages/index/template/regionalCategory/component/category'
import {getContent} from "../../utils/handlerPublicCode";
import './index.scss'

type StateType = {
  storeInfo: any
  pageGoods: Good[]
  loadMoreStatus: "more" | "loading" | "noMore"
  showLoading: boolean
  detail: any
  picture: any
  activeId: number
}

class Info extends Component {

  state: StateType = {
    storeInfo: {
      address: '',
      logo: '',
      service_tel: '',
      uuid: '',
      name: ''
    },
    pageGoods: [],
    loadMoreStatus: 'more',
    showLoading: true,
    detail: {},
    picture: [],
    activeId: -1
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this);
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    Taro.showLoading({title: '加载中...'})
    this.id = Taro.getCurrentInstance().router.params.uuid || ''
    const storeInfoData = await http.get<SiteInfo>(STORE_INFO, {uuid: this.id})
    let storeInfo = {}
    if (storeInfoData) {
      storeInfo = storeInfoData
    } else {
      const timer = setTimeout(() => {
        clearTimeout(timer)
      }, 1500)
    }
    const pageGoods = await this.getPageGoods(this.page)
    if (pageGoods && pageGoods.length > 0) {
      this.setState({activeId: 0})
    } else if(!(pageGoods && pageGoods.length > 0) && !!storeInfo.isStoreInfo) {
      this.getDateils()
      this.setState({activeId: 1})
    } else if (!(pageGoods && pageGoods.length > 0) && !storeInfo.isStoreInfo && !!storeInfo.shop_pitctures_number) {
      this.getPictures()
      this.setState({activeId: 2})
    }
    this.setState({pageGoods, showLoading: false, storeInfo})
    Taro.hideLoading()
  }

  id = ''
  page = 1
  total = 0

  async getPageGoods(page) {
    const pageGoodsData = await http.get<Good[]>(STORE_PAGE, {k: '', sid: this.id, p: page})
    if (pageGoodsData) {
      if (pageGoodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return pageGoodsData
    } else {
      return []
    }
  }

  async getDateils() {
    const api = '/msvc-shop/v1/application/shop/app/shop/introduction/' + this.id
    const res = await http.HGet(api);
    this.setState({
      detail: {
        ...res.data,
      },
    });
  }

  async getPictures() {
    const api = '/msvc-shop/v1/application/shop/app/shop/introduction/picture/' + this.id
    const res = await http.HGet(api);
    this.setState({picture: res.data.shop_pitctures ? res.data.shop_pitctures.split(',') : []});
  }

  makePhone() {
    Taro.makePhoneCall({
      phoneNumber: this.state.storeInfo.service_tel
    })
  }

  async navigate() {
    const {address = '', latitude = '', longitude = '', name} = this.state.storeInfo
    lxH5Wx.navigation(+latitude, +longitude, address, name)
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus !== 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const old = this.state.pageGoods
      const newData = await this.getPageGoods(this.page)
      this.setState({pageGoods: [...old, ...newData]})
    }
  }

  indexChange(index) {
    if (index === 1) {
      Taro.navigateTo({url: '/other/shop/details' + '?sid=' + this.id})
    }
    if (index === 2) {
      Taro.navigateTo({url: '/other/shop/picture' + '?sid=' + this.id})
    }
  }

  render() {
    const {storeInfo, pageGoods, showLoading, detail, picture, activeId} = this.state
    return (
      <View className='store-root'>
        <GzhAuth />
        <Skeleton loading={showLoading}
          title
          titleWidth='100%' rowHeight='375px'
        >
          <Block>
            <View className='header' />
            <View className='background-color'>
              <View className='head-box'>
                <View className='head-box-wrap'>
                  {storeInfo.logo && <Image className='head-img' src={storeInfo.logo} mode='aspectFill' />}
                  {!storeInfo.logo && <Image lazyLoad={process.env.TARO_ENV != "h5"}
                    src='https://resource.ivcheng.com/upload/2022/08/26/3d7e1b390cea425ca8a0d8f37c993d01.png'
                    mode='aspectFill' className='img-not'
                  />}
                  <View className='head-text'>
                    {!!storeInfo.name && <Text className='title'>{storeInfo.name}</Text>}
                    {storeInfo.application_open_comment == 1 && <View className='rate'>
                      {!!storeInfo.star && storeInfo.star > 0 && <AtRate
                        className={`star-rate ${process.env.TARO_ENV !== 'h5' ? 'star-rate-weapp' : ''}`}
                        value={storeInfo.star}
                        size={12}
                      />}
                      <View>{storeInfo.star && storeInfo.star > 0 ? Number(storeInfo.star).toFixed(1) : '暂无评分'}</View>
                      {storeInfo.consumption_per_person && <View className='person'>
                        ￥{storeInfo.consumption_per_person}/人
                      </View>}
                    </View>}
                  </View>
                </View>
              </View>
              {!!storeInfo.business_hours_intro && <View className='line' />}
              {!!storeInfo.business_hours_intro && <View className='head-info opening'>
                营业时间: {storeInfo.business_hours_intro}
              </View>}
              <View className='line' />
              <View className='head-info address'>
                <View>
                  <AtIcon value='map-pin' size='12' />
                  <Text>{storeInfo.address}</Text>
                </View>
                <View className='btn-box'>
                  {!!storeInfo.latitude && !!storeInfo.longitude && <View className='btn btn-go' onClick={this.navigate.bind(this)}>
                    <AtIcon prefixClass='xxhz' value='daohang' size='16' className='btn-icon' />
                    <Text className='btn-text'>导航</Text>
                  </View>}
                  <View className='btn btn-phone' onClick={this.makePhone.bind(this)}>
                    <AtIcon prefixClass='xxhz' value='phone' size='16' className='btn-icon' />
                    <Text className='btn-text'>电话</Text>
                  </View>
                </View>
              </View>
            </View>
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading} row={1} rowHeight={50}>
          <View className='nav-title'>
            {!!pageGoods && pageGoods.length > 0 && <View className={activeId === 0 ? 'title title-active' : 'title'}
              onClick={this.indexChange.bind(this, 0)}
            >商品</View>}
            {!!storeInfo.isStoreInfo && <View className={activeId === 1 ? 'title title-active' : 'title'}
              onClick={this.indexChange.bind(this, 1)}
            >商家</View>}
            {!!storeInfo.shop_pitctures_number && <View className={activeId === 2 ? 'title title-active' : 'title'}
              onClick={this.indexChange.bind(this, 2)}
            >图片({storeInfo.shop_pitctures_number})</View>}
          </View>
        </Skeleton>
        <Skeleton loading={showLoading} row={5} rowHeight={130}>
          <Block>
            {(pageGoods && pageGoods.length > 0) && <View className='other'>
              <View className='content'>
                <GoodsBox customClass='shopInfo' data={pageGoods} />
              </View>
            </View>}
            {/*{(pageGoods.length == 0) && <View className='listNull'>
              <Image src={`${RESOURCE_URL}/resources/images/carnull.png`} mode='widthFix' />
            </View>}*/}
          </Block>
          {!(pageGoods && pageGoods.length > 0) && !!storeInfo.isStoreInfo && <Block>
            <View className='info-product-detail'>
              <View className='product-detail-item-wrap'>
                <View style='padding: 10px 14px;background-color: #fff;border-radius: 6px;'>
                  <View className='rich-content' id='description'>
                    {TARO_ENV === 'weapp' && <View className='content-info content-info-no-l-r' style='padding-top: 0;padding-bottom: 0'>
                      <parser selectable html={detail.shop_introduction || ''} />
                    </View>}
                    {TARO_ENV === 'tt' && <View className='content-info content-info-no-l-r' style='padding-top: 0;padding-bottom: 0'>
                      <rich-text preview selectable nodes={getContent(detail.shop_introduction)} />
                    </View>}
                    {TARO_ENV === 'h5' && <Text selectable className='content-info content-info-no-l-r'>
                      {!!detail.shop_introduction &&
                      <View id='html-description' dangerouslySetInnerHTML={{__html: detail.shop_introduction}} />}
                    </Text>}
                  </View>
                </View>
              </View>
              <View style='height: 17px;' />
            </View>
          </Block>}
          {!(pageGoods && pageGoods.length > 0) && !storeInfo.isStoreInfo && !!storeInfo.shop_pitctures_number &&
          <Block>
            <View className='picture'>
              {picture.length > 0 && <View className='picture-box'>
                <View className='picture-img-left'>
                  {picture && picture.map((item, index) => <Block key={index}>
                    {index % 2 === 0 && <Image
                      className='left-image'
                      onClick={this.previewImage.bind(this, item)}
                      src={item}
                      lazyLoad
                      mode='widthFix'
                    />}
                  </Block>)}
                </View>
                <View className='picture-img-right'>
                  {picture && picture.map((item, index) => <Block key={index}>
                    {index % 2 !== 0 && <Image
                      className='right-image'
                      onClick={this.previewImage.bind(this, item)}
                      src={item}
                      lazyLoad
                      mode='widthFix'
                    />}
                  </Block>)}
                </View>
              </View>}
              {picture.length <= 0 && !showLoading && <View className='listNull'>
                <Image src={`${RESOURCE_URL}/resources/images/carnull.png`} mode='widthFix' />
              </View>}
              <View style='height: 17px;' />
            </View>
          </Block>
          }
        </Skeleton>
      </View>
    )
  }
}

export default Info as ComponentClass

